<template>
  <div class="business-file-manager">
    <h4>{{ title }}</h4>
    
    <!-- 文件上传组件 -->
    <FileUpload
      :multiple="false"
      :accept="accept"
      :max-size="maxSize"
      :current-file="currentFile"
      @upload-success="handleUploadSuccess"
      @file-removed="handleFileRemoved"
    />
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import FileUpload from './FileUpload.vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  // 标题
  title: {
    type: String,
    default: '文件管理'
  },
  // 接受的文件类型
  accept: {
    type: String,
    default: '.jpg,.jpeg,.png,.gif,.pdf,.doc,.docx'
  },
  // 文件大小限制
  maxSize: {
    type: Number,
    default: 10
  },
  // 当前文件信息
  fileInfo: {
    type: Object,
    default: null
  },
  // 业务ID
  businessId: {
    type: [String, Number],
    required: true
  },
  // 业务类型
  businessType: {
    type: String,
    required: true // supplier, user
  },
  // 文件类型
  fileType: {
    type: String,
    required: true // logo, license, certificate, avatar
  }
})

const emit = defineEmits(['file-changed', 'file-removed'])

const currentFile = ref(null)

// 监听文件信息变化
watch(() => props.fileInfo, (newValue) => {
  currentFile.value = newValue
}, { immediate: true })

// 处理文件上传成功
const handleUploadSuccess = (uploadResult) => {
  // 上传成功后，需要调用业务接口关联文件
  const fileData = Array.isArray(uploadResult) ? uploadResult[0] : uploadResult
  
  // 更新当前文件信息
  currentFile.value = {
    fileId: fileData.fileId,
    fileName: fileData.fileName,
    fileSize: fileData.fileSize,
    fileType: fileData.fileType,
    accessUrl: fileData.accessUrl,
    createTime: fileData.uploadTime
  }
  
  // 通知父组件文件已上传
  emit('file-changed', {
    fileId: fileData.fileId,
    fileType: props.fileType,
    fileInfo: currentFile.value
  })
  
  ElMessage.success('文件上传并关联成功')
}

// 处理文件删除
const handleFileRemoved = () => {
  currentFile.value = null
  emit('file-removed', props.fileType)
  ElMessage.success('文件删除成功')
}
</script>

<style scoped>
.business-file-manager {
  margin-bottom: 20px;
}

h4 {
  margin-bottom: 10px;
  color: #303133;
}
</style>